﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.ToolKit.StringHelper;

namespace MKAdminCore.Service.Web.Common
{
    public static class IDbConnectionExtensions
    {
        public static PagingList<T> QueryGetList<T>(this IDbConnection cnn,
            string sql, string orderSql = "Order By Id Desc",
            int pageIndex = 1, int pageSize = 20,
            object param = null)
        {
            var pagingList = new PagingList<T>();

            string sqlPagingCount = SqlPagingHelper.GetPagingCountSql(sql);
            string sqlPaging = SqlPagingHelper.GetPagingSql(sql, pageIndex, pageSize, orderSql);

            //获取总记录数
            pagingList.total = Convert.ToInt32(cnn.ExecuteScalar(sqlPagingCount, param) ?? 0);

            var query = cnn.Query<T>(sqlPaging, param);
            pagingList.data = query.ToList();

            return pagingList;
        }

        public static async Task<PagingList<T>> QueryGetListAsync<T>(this IDbConnection cnn,
            string sql, string orderSql = "Order By Id Desc",
            int pageIndex = 1, int pageSize = 20,
            object param = null)
        {
            var pagingList = new PagingList<T>();

            string sqlPagingCount = SqlPagingHelper.GetPagingCountSql(sql);
            string sqlPaging = SqlPagingHelper.GetPagingSql(sql, pageIndex, pageSize, orderSql);

            //获取总记录数
            pagingList.total = Convert.ToInt32(await cnn.ExecuteScalarAsync(sqlPagingCount, param) ?? 0);

            var query = await cnn.QueryAsync<T>(sqlPaging, param);
            pagingList.data = query.ToList();

            return pagingList;
        }
    }
}
